from flask import Flask, g
from flask import render_template
from flask import request
from flask import abort
import time
from syncpoint import syncpoint
from heartbeat import heartbeat
from command import command
from info import info
from golia import golia
from install import install
import sys
import config
import json
import random
from collections import defaultdict
import hashlib
from utils import get_real_addr

LOG = config.getlogger()
# cleaner.run_cleaner()
app = Flask(__name__)
app.register_blueprint(syncpoint, url_prefix='/sync')
app.register_blueprint(heartbeat, url_prefix='/heartbeat')
app.register_blueprint(command, url_prefix='/command')
app.register_blueprint(info, url_prefix='/info')
app.register_blueprint(golia, url_prefix='/golia')
app.register_blueprint(install, url_prefix='/install')


@app.route('/utils/<name>', methods=['GET'])
def utils(name=None):
    if name == 'timestamp':
        return '%f' % time.time()
    elif name == 'address':
        return get_real_addr()
    else:
        abort(404)


@app.route('/', methods=['GET'])
def echo():
    addr = get_real_addr()
    LOG.debug('request from %s' % addr)
    return addr


@app.route('/reg', methods=['GET', 'POST'])
def reg_agent():
    return 'ok'


if __name__ == '__main__':
    port = int(sys.argv[1])
    app.run(host='0.0.0.0', port=port, debug=True)
